<template>
    <PageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="pageData.headerShow">
                <a-form size="mini" :model="pageData" layout="inline">
                    <a-form-item label="仓库类型">
                        <a-select popup-container="html"  :style="{ width: '10rem' }" @change="whChange" placeholder=""
                            v-model="searchData.whTypeName" allow-clear>
                            <a-option v-for="item in whTypeList" :value="item.typeName">
                                {{ item.typeName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="选择公司">
                        <a-select popup-container="html"  :style="{ width: '10rem' }" @change="companyChange" placeholder=""
                             v-model="searchData.firm" allow-clear>
                            <a-option v-for="item in companyList" :value="item.id">
                                {{ item.typeName ? item.typeName+ '-'+item.firmName : item.firmName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="仓库">
                        <a-select popup-container="html"  :style="{ width: '10rem' }" placeholder="" v-model="searchData.wh" @click="ckisPd" @change="isWhilist" allow-clear>
                            <a-option v-for="item in whList" :value="item.warehouseName">
                                {{ item.warehouseName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="转仓状态">
                        <a-select popup-container="html"  :style="{ width: '10rem' }" placeholder="" v-model="searchData.stats" allow-clear>
                            <a-option :value="0">待转入</a-option>
                            <a-option :value="1">已转入</a-option>
                            <a-option :value="2">已转出</a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="pageData.headerShow" @click="pageData.headerShow = false" :strokeWidth="2"
                        :size="18" />
                    <icon-double-down v-else @click="pageData.headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '新增']" @add="addHandler" @del="" @select="selectHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true">
                <a-tab-pane title="转仓单">
                    <a-table :style="{
                        height: '100%'
                    }" size="mini" :scrollbar="true" sticky-header @page-change="pagination.change" stripe
                        :bordered="true" :columns="baseCol"
                        :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                        v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                        :pagination="{ size: 'mini', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total }"
                        rowKey="orderNo">
                        <template #action="{ record }">
                            <a-space>
                                <a-button v-if="record.auditState === 0" type="primary" size="mini" status="warning"
                                    @click="xingXg(record)">
                                    <template #icon>
                                        <icon-edit />
                                    </template>
                                    修 改
                                </a-button>
                                <a-button v-else type="primary" size="mini" status="warning" disabled>
                                    <template #icon>
                                        <icon-edit />
                                    </template>
                                    修 改
                                </a-button>
                                <a-button type="primary" size="mini" @click="dyingMx(record)">
                                    <template #icon>
                                        <icon-archive />
                                    </template>
                                    打印
                                </a-button>
                                <a-button type="outline" status="success" size="mini"
                                    @click="isXiang(record)">
                                    <template #icon>
                                        <icon-find-replace />
                                    </template>
                                    详情
                                </a-button>
                                <a-button type="outline" v-if="record.auditState == 0 || record.auditState == 1" size="mini"
                                    @click="deletWh(record)">
                                    <template #icon>
                                        <icon-delete />
                                    </template>
                                    删除
                                </a-button>
                                <a-button type="outline" v-else size="mini" disabled>
                                    <template #icon>
                                        <icon-delete />
                                    </template>
                                    删除
                                </a-button>
                            </a-space>
                        </template>
                        <template #auditState="{ record }">
                            <a-button v-if="(record.auditState == 0)" type="primary" status="warning" size="mini"
                                disabled>待&nbsp;审&nbsp;核&nbsp;
                            </a-button>
                            <a-button v-if="(record.auditState == 2)" status="success" size="mini"
                                disabled>审核通过</a-button>
                            <a-button v-if="(record.auditState == 1)" type="primary" size="mini" status="danger"
                                disabled>审核驳回
                            </a-button>
                        </template>
                    </a-table>
                </a-tab-pane>
            </a-tabs>
        </template>
        <a-drawer ok-text='保存' cancel-text='关闭' :style="{ 'zIndex': 999 }" :mask-closable="false" :height="600"
            :visible="pageData.showAdd" unmountOnClose @ok="sicksOk" placement="bottom" @cancel="sicksNo">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-space>
                    <a-button size="mini" type="primary" @click="tjWlzl">添加</a-button>
                </a-space>
                <div style="height:10px ;"></div>
                <a-table :style="{
                    height: '100%',
                    marginTop: '10px'
                }" stripe :bordered="true" :scrollbar="true" :pagination="false" sticky-header :columns="tableColumns"
                    :data="tableSjList">
                    <template v-for="(item, index) in tableColumns" #[item.slotName]="{ record }">
                        <div v-if="(item.ls != '' && item.dropState == 1)">
                            <a-select popup-container="html"  v-model="record[item.slotName]" allow-clear @click="dongTypeSelce(record, item)"
                                @change="changsType(item, record)">
                                <a-option v-for="items in isDtas" :value="items[item.slotName]">
                                    {{ items[(item.slotName)] }}
                                </a-option>
                            </a-select>
                        </div>
                        <div v-else-if="(item.ls != '' && item.dropState == 0)">
                            <a-input disabled v-model="record[item.slotName]"></a-input>
                        </div>
                        <div v-else-if="(item.ls == '' || item.ls == undefined && index != tableColumns.length - 1)">
                            <a-input v-model="record[item.slotName]"></a-input>
                        </div>
                        <a-button v-if="(index == tableColumns.length - 1)" type="outline" size="mini"
                            @click="deletWhsWl(record)">
                            <template #icon>
                                <icon-delete />
                            </template>
                            删除
                        </a-button>
                    </template>
                </a-table>
            </div>
        </a-drawer>
        <a-modal v-model:visible="visible" title="详情" :width="1200" :footer="false" :draggable="true">
            <a-table :style="{
                height: '500px',
                marginTop: '10px'
            }" stripe :bordered="true" :scrollbar="true" sticky-header :pagination="false" :columns="tableColumns1"
                :data="whListMingxs">
            </a-table>
        </a-modal>
        <a-modal v-model:visible="visiblecg" ok-text="打印" @ok="print" @cancel="cancels" :width="800">
            <template #title>
                入库单打印
            </template>
            <div id="receiptList1">
                <div id="dys">
                    <QrcodeVue :value="qrData.code"></QrcodeVue>
                    <div>
                        <p>打印人:&nbsp;&nbsp;{{ qrData.dyData }}</p>
                        <p>打印时间:&nbsp;&nbsp;{{ qrData.dyTime }}</p>
                        <p>单号:&nbsp;&nbsp;{{ qrData.dyCode }}</p>
                    </div>
                </div>
                <table class="isTable">
                    <tr>
                        <th v-for=" item in btList">{{ item[Object.keys(item)[0]] }}</th>
                    </tr>
                    <tr v-for="items in jsList">
                        <td v-for="item in btList">{{ items[Object.keys(item)[0]] }}</td>
                    </tr>
                </table>
            </div>
        </a-modal>
    </PageTabelLayout>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, h, watch } from "vue";
import Toolbar from "@/components/Toolbar.vue";

import PageTabelLayout from "@/components/pageTabelLayout.vue";
import TreeUtils from "@/utils/TreeUtils";

import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { Message, Modal } from "@arco-design/web-vue";
import { tableColumns } from "@/components/processrowfactory/useTableList";
import { IconDoubleUp, IconDoubleDown, IconEdit, IconFindReplace, IconDelete } from "@arco-design/web-vue/es/icon";
import pagination from "@arco-design/web-vue/es/pagination";
import { table } from "console";
import QrcodeVue from 'qrcode.vue'
import printJS from 'print-js'


export default {
    name: "SpecialReceiptList",

    setup() {

        const whService = new WHService()
        const whList = ref<any[]>([])
        const whTypeList = whService.whTypeList

        const whTypeFieldList = whService.whTypeFieldList
        const treeUtils = new TreeUtils()
        const companyList:any = whService.companyList
        const searchData = reactive<{
            whTypeName: string;
            firm: string,
            wh: string,
            stats:any
        }>({
            firm: '',
            whTypeName: "",
            wh: '',
            stats:null
        });

        const baseCol: any[] = [{
            dataIndex: 'orderNo',
            key: 'orderNo',
            title: '单据编号',
            width: 180
        }, {
            dataIndex: 'firm',
            key: 'firm',
            title: '公司',
            width: 150
        }, {
            dataIndex: 'warehouseTypeName',
            key: 'warehouseTypeName',
            title: '仓库类型',
            width: 150
        },
        {
            dataIndex: 'warehouseName',
            key: 'warehouseName',
            title: '仓库',
            width: 150
        }
            , {
            dataIndex: 'auditName',
            key: 'auditName',
            title: '审核人',
            width: 100
        }, {
            title: '审核时间',
            dataIndex: 'auditTime',
            key: 'auditTime',
            width: 100
        }, 
        {
            title: '单据状态',
            dataIndex: 'infoState',
            key: 'infoState',
            width: 150
        },
        {
            title: '创建人',
            dataIndex: 'createName',
            key: 'createName',
            width: 150
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 150
        },
        {
            title: '修改人',
            dataIndex: 'updateName',
            key: 'updateName',
            width: 150
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 150
        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            slotName: 'auditState',
            width: 100,
            key: 'auditState',
            fixed: "right",
        },
        {
            title: '详情',
            fixed: "right",
            slotName: 'action',
            width: 280
        }]

        function doRefresh() {
            pageData.pageLoading = true;
            post({
                url: "wms/WarehousetypeFieldvalue/getInvoicesByPage",
                data: {
                    "page": pagination.page,
                    "size": pagination.pageSize,
                    "warehouseTypeName": searchData.whTypeName,
                    "firmId": searchData.firm,
                    "infoType": 3,
                    'infoState':searchData.stats
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        pagination.setTotalSize(data.total);
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false;
                });
        }



        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        let tableColumns: any = ref([])
        let tableColumns1: any = ref([])
        let tableListDatas = reactive({
            typeLesIds:0
        })
        watch(() => whService.whTypeFieldList.value, () => {
            //  baseCol.splice(3,0, ...(whService.whTypeFieldList.value.map((f:any)=>{
            //     return {
            //         dataIndex:f.extendField,
            //         key:f.extendField,
            //         title:f.fieldName,
            //         width:150
            //     }
            // })))
            tableColumns.value = whService.whTypeFieldList.value.map((f: any) => {
                return {
                    dataIndex: f.englishName,
                    key: f.englishName,
                    title: f.chineseName,
                    slotName: f.englishName,
                    width: 150,
                    ls: f.ls,
                    dropState: f.dropState,
                    conditions: f.conditions
                }
            })
            tableColumns1.value = whService.whTypeFieldList.value.map((f: any) => {
                return {
                    dataIndex: f.englishName,
                    key: f.englishName,
                    title: f.chineseName,
                    slotName: f.englishName,
                    width: 150,
                }
            })
            tableColumns1.value.unshift({
                dataIndex: 'orderNo',
                key: 'orderNo',
                title: '单据编号',
                width: 180
            }
            // , {
            //     dataIndex: 'firm',
            //     key: 'firm',
            //     title: '公司',
            //     width: 150
            // }, {
            //     dataIndex: 'warehouseTypeName',
            //     key: 'warehouseTypeName',
            //     title: '仓库类型',
            //     width: 150
            // },
            //     {
            //         dataIndex: 'warehouseName',
            //         key: 'warehouseName',
            //         title: '仓库',
            //         width: 150
            //     }
                )
            tableColumns.value.push(
                {
                    title: '操作',
                    fixed: "right",
                    slotName: 'action',
                    width: 150
                }
            )
            whService.whTypeFieldList.value.forEach((item: any) => {
                tableListDatas[item.englishName] = ''
            })
            

        })


        const pageData = reactive<{
            showAdd: boolean
            sideTitle: string
            pageLoading: boolean
            headerShow: boolean

        }>({
            showAdd: false,
            sideTitle: "新增转仓单",
            pageLoading: false,
            headerShow: true
        })

        const addHandler = () => {
            if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '') {
                Message.error('请先选择主页仓库类型或选择公司或仓库')
            } else {
                pageData.sideTitle = '新增转仓单'
                pageData.showAdd = true
            }
        }
        const selectHandler = () => {
            if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '') {
                Message.error('请先选择主页仓库类型或选择公司或仓库')
            } else {
                doRefresh()
            }
        }
        const whChange = () => {
            whList.value = []
            searchData.wh = ''
            searchData.firm = ''
        }
        watch(() => whService.whList.value, (o, n) => {


            whList.value = whService.whList.value
        })
        // 公司下拉框 改变
        const companyChange = (val: any) => {
            whList.value = []
            searchData.wh = ''
            whService.getWarhouseList(searchData.firm, searchData.whTypeName)
        }

        let visible = ref(false)
        let whListMingxs = ref<any[]>([])
        const isXiang = async (val: any) => {
            const res: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
            if (res.code == 200) {
                whListMingxs.value = res.data
                visible.value = true
            }
        }
        let tableSjList: any = ref([])
        const tjWlzl = () => {
            tableListDatas.typeLesIds++
            tableSjList.value.push(JSON.parse(JSON.stringify(tableListDatas)))
        }
        const sicksOk = async () => {
            tableListDatas.typeLesIds = 0
            if (pageData.sideTitle == '新增转仓单') {
                tableSjList.value.forEach((item: any) => {
                    item['warehouseTypeName'] = searchData.whTypeName
                    item['warehouseName'] = searchData.wh
                    item['firm'] = searchData.firm
                    item['infoType'] = 3
                })
                const res: any = await whService.addWarhouseMinxList(tableSjList.value)
                if (res.code == 200) {
                    tableSjList.value = []
                    doRefresh()
                    Message.success('添加成功')
                    pageData.showAdd = false
                } else {
                    Message.error(res.message)
                }
            } else if (pageData.sideTitle == '修改转仓单') {
                tableSjList.value.forEach((item: any) => {
                    item['warehouseTypeName'] = searchData.whTypeName
                    item['warehouseName'] = searchData.wh
                    item['firm'] = searchData.firm
                    item['infoType'] = 3
                    item['orderNo'] = orderNos
                    item['createName'] = tableSjList.value[0].createName
                    item['createTime'] = tableSjList.value[0].createTime
                })
                let updataWhdataList = {
                    warehouseTypeName: searchData.whTypeName,
                    warehouseName: searchData.wh,
                    firm: searchData.firm,
                    updateInfo: tableSjList.value
                }
                const res: any = await whService.updataWarhouseMinxList(updataWhdataList)
                if (res.code == 200) {
                    orderNos = ''
                    tableSjList.value = []
                    doRefresh()
                    Message.success('修改成功')
                    pageData.showAdd = false
                } else {
                    Message.error(res.message)
                }
            }
        }
        const sicksNo = () => {
            tableListDatas.typeLesIds = 0
            tableSjList.value = []
            pageData.showAdd = false
        }
        let orderNos: any;
        const xingXg = async (val: any) => {
            orderNos = val.orderNo
            const res = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
            if (res.code == 200) {
                tableSjList.value = res.data
                pageData.sideTitle = '修改转仓单'
                pageData.showAdd = true
            }
        }

        const deletWh = (val: any) => {
            let objDelet = {
                warehouseTypeName: val.warehouseTypeName,
                warehouseName: val.warehouseName,
                firm: val.firm,
                delOrderNoInfo: [val.orderNo]
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk: async () => {
                    const res: any = await whService.deletWarhouseMinxList(objDelet)
                    if (res.code == 200) {
                        Message.success('删除成功')
                        doRefresh()
                    } else {
                        Message.error(res.message)
                    }
                }
            })
        }
        const deletWhsWl = (val: any) => {
            let objDelet = {
                warehouseTypeName: val.warehouseTypeName,
                warehouseName: val.warehouseName,
                firm: val.firm,
                delInfo: [val.id]
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk: async () => {
                    if (val.id == undefined) {
                        tableSjList.value.forEach((item:any,index:any)=>{
                             if(val.typeLesIds == item.typeLesIds){
                                tableSjList.value.splice(index,1)
                             }
                        })
                        if(tableSjList.value.length ==0){
                            pageData.showAdd = false
                        }
                    } else {
                        const res: any = await whService.deletWhmxWarhouseMinxList(objDelet)
                        if (res.code == 200) {
                            Message.success('删除成功')
                            const resz: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
                            if (resz.code == 200) {
                                if (resz.data.length == 0) {
                                    whListMingxs.value = resz.data
                                    tableSjList.value = resz.data
                                    doRefresh()
                                    pageData.showAdd = false
                                } else {
                                    whListMingxs.value = resz.data
                                    tableSjList.value = resz.data
                                }
                            }
                        } else {
                            Message.error(res.message)
                        }
                    }
                }
            })
        }
        const visiblecg = ref(false)
        const zsList: any = ref([])
        const btList: any = ref<any[]>([])
        const jsList: any = ref([])
        const qrData = reactive({
            dyTime: '',
            dyData: '',
            dyCode: '',
            code: ''
        })
        const dyingMx = async (val: any) => {
            let isDataObj = {
                "warehouseTypeName": val.warehouseTypeName,
                "warehouseName": val.warehouseName,
                "firm": val.firm,
                "orderNo": val.orderNo
            }
            const res: any = await whService.DyWhmxWarhouse([isDataObj])
            if (res.code == 200) {
                zsList.value = res.data
                qrData.dyTime = res.data[0].printTime
                qrData.dyData = res.data[0].printName
                qrData.dyCode = res.data[0].orderNo
                qrData.code = JSON.stringify({ warehouseCode: encodeURI(res.data[0].warehouseCode), warehouseTypeCode: encodeURI(res.data[0].warehouseTypeCode), orderNo: encodeURI(res.data[0].orderNo),infoType:Number(3) })
                for (let item in res.data[0].tableHead) {
                    btList.value.push({
                        [item]: res.data[0].tableHead[item]
                    })
                }
                jsList.value = res.data[0].info
                console.log(jsList.value)
                visiblecg.value = true
            }
        }
        const print = () => {
            printJS({
                printable: 'receiptList1',
                type: 'html',
                targetStyles: ['*'],
            })
            zsList.value = []
            btList.value = []
            jsList.value = []
            for (let item in qrData) {
                qrData[item] = ''
            }
        }
        const cancels = () => {
            zsList.value = []
            btList.value = []
            jsList.value = []
            for (let item in qrData) {
                qrData[item] = ''
            }
        }
        let isDtas = ref([])
        const dongTypeSelce = async (record: any, val: any) => {
            var paramList: any = [];
            var ob: any = {};
            if (val.conditions.length > 0) {
                let conditions = val.conditions
                for (let i = 0; i < conditions.length; i++) {
                    if (conditions[i].extendField != null && conditions[i].extendField != "") {
                        if (record[conditions[i].extendField] == null || record[conditions[i].extendField] == "") {
                            let column = tableColumns.value.filter(function (o: any) {
                                return o.key == conditions[i].extendField;
                            })[0];
                            Message.error("请先输入" + column.title)
                            return;
                        } else {
                            ob[conditions[i].extendField] = record[conditions[i].extendField];
                        }
                    }
                }

            }
            ob["ls"] = val.ls;
            paramList.push(ob);
            const res = await whService.liusuiCkSmWhmxWarhouse(paramList)
            if (res.code == 200) {
                isDtas.value = res.data[val.ls]
            }
        }
        const changsType = (ob: any, record: any) => {
            if (record[ob.slotName] == "") {
                for (let key in isDtas.value[0]) {
                    record[key] = ""
                }
            } else {
                isDtas.value.forEach((item: any) => {
                    if (item[ob.slotName] == record[ob.slotName]) {
                        for (let key in item) {
                            record[key] = item[key]
                        }
                    }
                })
            }
        }
        const ckisPd = ()=>{
            if(searchData.whTypeName =='' ||searchData.firm==''){
                Message.error('请先选择仓库类型和所属工厂')
                return
            }
        }
        const isWhilist = (whName:any)=>{
            let isWhId;
            whList.value.forEach((item:any)=>{
                if(whName ==item.warehouseName){
                    isWhId = item.id
                }
            })
            whService.loadWHTypeFieldList({warehouseId:isWhId,showType:3})
        }
        return {
            isWhilist,
            ckisPd,
            changsType,
            isDtas,
            dongTypeSelce,
            qrData,
            cancels,
            zsList,
            btList,
            jsList,
            print,
            visiblecg,
            dyingMx,
            deletWhsWl,
            deletWh,
            xingXg,
            sicksNo,
            sicksOk,
            tableSjList,
            tableListDatas,
            tjWlzl,
            whListMingxs,
            isXiang,
            visible,
            companyChange,
            whChange,
            selectHandler,
            addHandler,
            companyList,
            whList,
            whTypeList,
            selectedRowKeys,
            whTypeFieldList,
            pagination,
            tableColumns,
            tableColumns1,
            table,
            rowKey,
            pageData,
            searchData,
            baseCol
        };
    },
    components: { PageTabelLayout ,QrcodeVue}
};
</script>
<style scoped lang="less">
.isTable {
    margin-top: 100px;
    width: 90%;
    margin: 0 auto;
    border: 1.2px solid #ccc;
    text-align: center;
    border-collapse: collapse;

    td {
        border: 1.2px solid #ccc;
    }

    th {
        border: 1.2px solid #ccc;
    }
}
#receiptList1{
    width: 100%;
    #dys{
    width: 90%;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
}
}
</style>
